//
//  VideoViewController.m
//  FlowerRainGround
//
//  Created by 阿仁欧巴 on 16/4/20.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "VideoViewController.h"
#import "VideoTableViewCell.h"
#import "DetailViewController.h"

@interface SDWebImageManager  (cache)


- (BOOL)memoryCachedImageExistsForURL:(NSURL *)url;

@end

@implementation SDWebImageManager (cache)

- (BOOL)memoryCachedImageExistsForURL:(NSURL *)url {
    NSString *key = [self cacheKeyForURL:url];
    return ([self.imageCache imageFromMemoryCacheForKey:key] != nil) ?  YES : NO;
}

@end

@interface VideoViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation VideoViewController

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataArray;
}
- (void)requestData
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:@"http://m.htxq.net/servlet/SysArticleServlet" parameters:@{@"action":@"mainList", @"currentPageIndex":@"0", @"isVideo":@"true", @"pageSize":@"5"} progress:^(NSProgress * _Nonnull uploadProgress) {
        
//action=mainList&currentPageIndex=0&isVideo=true&pageSize=5
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *mDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        
        NSArray *array = mDic[@"result"];
        for (NSDictionary *dic in array) {
            VideoModel *model = [[VideoModel alloc] init];
            CategoryModel *cateModel = [[CategoryModel alloc] init];
            model.categaryModel = cateModel;
            [cateModel setValuesForKeysWithDictionary:dic[@"category"]];
            [model setValuesForKeysWithDictionary:dic];
            [self.dataArray  addObject:model];
        }
        
        [SVProgressHUD dismiss];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];

}




- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestData];
    [SVProgressHUD show];
    
    //注册cell
    [_tableView registerClass:[VideoTableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    
 
    
    
    // Do any additional setup after loading the view from its nib.
}

#pragma mark ----tableView 的 delegate datasource -----


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 250;
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    return cell;
}
//添加每个cell出现时的3D动画
- (void)tableView:(UITableView *)tableView willDisplayCell:(VideoTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    VideoModel *model = self.dataArray[indexPath.row];
    
    if (![[SDWebImageManager sharedManager] memoryCachedImageExistsForURL:[NSURL URLWithString:model.smallIcon]]) {
        
        CATransform3D rotation;//3D旋转
        
        rotation = CATransform3DMakeTranslation(0 ,50 ,20);
        //        rotation = CATransform3DMakeRotation( M_PI_4 , 0.0, 0.7, 0.4);
        //逆时针旋转
        
        rotation = CATransform3DScale(rotation, 0.9, .9, 1);
        
        rotation.m34 = 1.0/ -600;
        
        cell.layer.shadowColor = [[UIColor blackColor]CGColor];
        cell.layer.shadowOffset = CGSizeMake(10, 10);
        cell.alpha = 0;
        
        cell.layer.transform = rotation;
        
        [UIView beginAnimations:@"rotation" context:NULL];
        //旋转时间
        [UIView setAnimationDuration:0.6];
        cell.layer.transform = CATransform3DIdentity;
        cell.alpha = 1;
        cell.layer.shadowOffset = CGSizeMake(0, 0);
        [UIView commitAnimations];
    }
    
    [cell cellOffset];
    cell.model = model;
}

//表视图滚动时

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    NSArray<VideoTableViewCell *> *array = [self.tableView visibleCells];
    
    [array enumerateObjectsUsingBlock:^(VideoTableViewCell * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj cellOffset];
    }];
    
}


#pragma mark ---点击cell 的方法 ---

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *model = self.dataArray[indexPath.row];
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    detailVC.videoModel = model;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
